#include "imagewidget.h"
#include <QUrl>
#include <QDir>
#include <QFileDialog>
#include <QtEvents>
#include <QDrag>
#include <QDropEvent>
#include <QMimeData>
#include <QDragEnterEvent>
#include <QDragLeaveEvent>
#include <QDragMoveEvent>
#include <QPixmap>
#include <QImage>

#include "c_cifar10_client.h"

ImageWidget::ImageWidget(QWidget *parent) :
    QLabel(parent),
    imgFileList(new QStringList),
    m_HistoryDir(new QString)
{
    this->setAlignment(Qt::AlignCenter);
    this->setAcceptDrops(1);
    *m_HistoryDir = QDir::homePath();
}

ImageWidget::~ImageWidget()
{
    delete imgFileList;
    delete m_HistoryDir;
}

void ImageWidget::getOpenFiles()
{
    QString *filesfilter = new QString("PNG Image(*.png);;BMP Image(*.bmp);;JPEG Image(*.jpeg *.jpg);;PBM Image(*.pbm);;PGM Image(*.pgm);;All Files(*.*)");

    imgFileList->clear();
    *imgFileList = QFileDialog::getOpenFileNames(this,
                                                 tr("Select Files"),
                                                 *m_HistoryDir,
                                                 *filesfilter);
    if(!imgFileList->isEmpty()){
        QFileInfo file(imgFileList->at(0));
        *m_HistoryDir = file.absolutePath();
        emit imageList(*imgFileList);
    }
}

void ImageWidget::mouseReleaseEvent(QMouseEvent *e)
{
    if(Qt::LeftButton == e->button()){
        getOpenFiles();
    }
    QLabel::mouseReleaseEvent(e);
}

void ImageWidget::dropEvent(QDropEvent *e)
{
    QList <QUrl>urls;
    urls = e->mimeData()->urls();
    if(!urls.isEmpty()){
        imgFileList->clear();
        foreach(QUrl url, urls) {
            QString imgFileName = url.toLocalFile();
            imgFileList->append(imgFileName);
        }
        emit imageList(*imgFileList);
    }
}

void ImageWidget::dragEnterEvent(QDragEnterEvent *e)
{
    if(e->mimeData()->hasFormat("text/uri-list")){
        e->acceptProposedAction();
    }
}

void ImageWidget::dragLeaveEvent(QDragLeaveEvent *e)
{

}

void ImageWidget::dragMoveEvent(QDragMoveEvent *e)
{

}
